package com.wica.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.codecarpet.fbconnect.FBLoginButton;
import com.codecarpet.fbconnect.FBSession;
import com.wica.adapter.ELAPersonalizedSearch;
import com.wica.adapter.ELASearch;
import com.wica.facebook.Facebook;
import com.wica.facebook.Facebook.FBSessionDelegateImpl;
import com.wica.facetube.FaceTubeService;
import com.wica.facetube.R;
import com.wica.view.tab_preference.TabPreferencesSearch;

public class ELSearch extends EfficientList {

	// *************** Constants ************** //  
	// Tab settings constants
    private static final int MENU_SEARCH = Menu.FIRST;
	private static final int MENU_SETTINGS = Menu.FIRST+1;
	private static final int MENU_SET_MOOD = Menu.FIRST+2;
	private static final int MENU_SET_TEXTLOCATION = Menu.FIRST+3;
    // Menu mode spinner choices
    // This list must match the list found in /res/values/arrays.xml
    final static int ORDER_BY_RELEVANCE = 11;
    final static int ORDER_BY_VIEWCOUNT = 12;
    final static int ORDER_BY_RATING = 13;
    final static int PERSONALIZED = -1;
	// Log constants
	protected static final String LOG_TAG = "PTv.ELSearch";	
    private static final String kApiKey = "9209dc6a3ee783213152ab316074b52e"; // "<YOUR API KEY>";
    // Enter either your API secret or a callback URL (as described in documentation):
    private static final String kApiSecret = "5fafeccf3bcae3e59773468cd82fd250"; // "<YOUR SECRET KEY>";    
	private static final int LOG_OFF_FACEBOOK = Menu.FIRST+4;
	private static final int REQUESTCODE_FACEBOOK = 2;	
    private FBSession _session;
    private FBLoginButton _loginButton;
	private FBSessionDelegateImpl fbs;

    // *************** Attributes ************************* //
	private Integer userID;
    public AlertDialog alertDialog;
    private String searchString;
    private Integer orderBy;
	public EditText edit;
	protected AlertDialog dialog2;
	
	// *************** Methods **************************** //	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Toast.makeText(this, "Press MENU button to get more options.", Toast.LENGTH_LONG).show();
        userID=PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1);
        searchString=this.getIntent().getStringExtra("searchString");
        
        if (searchString=="__empty"){
        	//lo que voy a hacer es crear una nueva actividad (como en API DEMOS-activity-Dialog) que nos devuelve el searchstring
			//con el searchstring establezco el adapter con lo cual sigo la estructura de most viewed
			//luego puedo invocar otra vez la actividad desde el menu
        	searchString="flag";
        	// DialogActivity calls onActivityResult method on return
        	this.startActivityForResult(new Intent(this, DialogActivity.class), MENU_SEARCH);        	
        }
    }// oncreate method
	
	@Override
	protected void  onActivityResult  (int requestCode, int resultCode, Intent data){
		Log.v(LOG_TAG, LOG_TAG2+"onActivityResult__"+requestCode);
		switch (requestCode) {
		case MENU_SEARCH:
	        Bundle bundle = data.getExtras();
	        Log.v(LOG_TAG, LOG_TAG2+"onActivityResult2__"+(String)bundle.get("searchString"));
	        searchString=(String)bundle.get("searchString");
	        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	        String pref = sharedPreferences.getString("list_search_preference", "personalized");
	        if (searchString.compareTo("")==0){
		        Log.v(LOG_TAG, LOG_TAG2+"onActivityResult3.1__"+(String)bundle.get("searchString"));

//	    		this.startActivityForResult(new Intent(this, DialogActivity.class), REQUESTCODE_SEARCH);
		        Toast.makeText(this, "More options by pressing MENU button", Toast.LENGTH_LONG).show();
	        }else{
		        Log.v(LOG_TAG, LOG_TAG2+"onActivityResult3.2__"+(String)bundle.get("searchString"));

	        	if (pref.compareTo("relevance")==0){
	        		orderBy=ORDER_BY_RELEVANCE;
	        		setListAdapter(new ELASearch((ELSearch)this,searchString,orderBy));
	        	}else if (pref.compareTo("viewcount")==0){
	        		orderBy=ORDER_BY_VIEWCOUNT;
	        		setListAdapter(new ELASearch((ELSearch)this,searchString,orderBy));
	        	}else if (pref.compareTo("rating")==0){
	        		orderBy=ORDER_BY_RATING;
	        		setListAdapter(new ELASearch((ELSearch)this,searchString,orderBy));
	        	}else{
	        		orderBy=PERSONALIZED;
	        		setListAdapter(new ELAPersonalizedSearch((ELSearch)this,searchString));
	        	}
	        }
			break;
		case MENU_SET_MOOD:
			break;
		case REQUESTCODE_FACEBOOK:
	       	Editor s;
			Bundle bundle2;
			Long facebookID;
			FaceTubeService facetube;
			Long userID;
   			bundle2 = data.getExtras();
   			facebookID=(Long)bundle2.get("userID");
  			facetube = new FaceTubeService();
  			userID = facetube.faceTubeFacebookID2userID(facebookID);
   			s = PreferenceManager.getDefaultSharedPreferences(this).edit();
   			s.putInt("userID",Integer.valueOf(userID.toString()));
   			s.commit();
   			Intent intent = new Intent(this,InitialConfiguration.class);
   			this.startActivity(intent);
   			break;
		}
    }    
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        // Build the menu shown when we hit menu button (KeyEvent class - KEYCODE_MENU) while playing the video.
        menu.add(0, MENU_SEARCH, 0, R.string.search_in_list)
        		.setShortcut('0', 'r')
        		.setIcon(android.R.drawable.ic_search_category_default);
        menu.add(0, MENU_SET_MOOD, 1, R.string.set_mood)
				.setShortcut('0', 'r')
				.setIcon(R.drawable.stat_happy);
        menu.add(0, MENU_SET_TEXTLOCATION, 2, R.string.set_textLocation)
        		.setShortcut('0', 'r')
        		.setIcon(R.drawable.menu_location_by_text);
        menu.add(0, MENU_SETTINGS, 3, R.string.settings)
        		.setShortcut('0', 'r')
        		.setIcon(R.drawable.ic_settings);
//        menu.add(0, LOG_OFF_FACEBOOK, 2, "Sign out")
//		.setShortcut('0', 'r')
//		.setIcon(R.drawable.log_off);
        return true;
    }    
   
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle all of the possible menu actions.
        switch (item.getItemId()) {
        case MENU_SEARCH:
        	this.startActivityForResult(new Intent(this, DialogActivity.class), MENU_SEARCH);        	
        	break;
        case MENU_SETTINGS:
        	this.startActivity(new Intent(this, TabPreferencesSearch.class));
        	break;
        case MENU_SET_MOOD:
        	this.startActivity(new Intent(this, MoodDialog.class));
            break;
    	case MENU_SET_TEXTLOCATION:
    		this.startActivity(new Intent(this, TextLocationDialog.class));
    		break;
		case LOG_OFF_FACEBOOK:
        	Editor s = PreferenceManager.getDefaultSharedPreferences(this).edit();
        	s.remove("userID");
        	s.commit();
    		this.startActivityForResult(new Intent(this,Facebook.class),REQUESTCODE_FACEBOOK);
        	break;
        }
        return super.onOptionsItemSelected(item);
    }
	
	@Override
	protected void  onPause  ()  {
		super.onPause();
		searchString="__empty";
	}
	
	@Override
	protected void  onStart  ()  {
		super.onStart();
		searchString="__empty";
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.v(LOG_TAG,LOG_TAG2+"resume"+searchString);
		if (searchString.compareTo("")==0)
	        Toast.makeText(this, "More options by pressing MENU button", Toast.LENGTH_LONG).show();
		else if (searchString.compareTo("__empty")!=0||!internetNetworkAvailable()){
			
		}else {
//			this.startActivityForResult(new Intent(this, DialogActivity.class), MENU_SEARCH);
			searchString="__empty";
		}		 
	}//onResume	

    protected boolean internetNetworkAvailable() {
        // Local Variables
    	ConnectivityManager connectivityManager = (ConnectivityManager)(((Context)this).getSystemService(Context.CONNECTIVITY_SERVICE));
        NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
        int i;
        
        for (i=0;i<allNetworkInfo.length;i++){
        	NetworkInfo networkInfoItem = allNetworkInfo[i];        	
            if (networkInfoItem.isAvailable()){
            	return true;
            }// if
        }// for
		return false;
	}// internetNetworkAvailable method
	
	@Override
	protected String getListTimeSetting() {
		return PreferenceManager.getDefaultSharedPreferences((Context)this).getString("list_search_preference", "personalized");
	}
    
}//EfficientListPersonalizedSearch